<?php

namespace app\admin\controller;

use app\admin\model\AdminLog;
use app\common\controller\Backend;
use fast\Random;
use think\Db;
use think\Env;
use think\Exception;
use \app\admin\model\Agent as AgentModel;
use think\Validate;

class Agent extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,name,title';

    protected $with = ['bank'];

    /**
     * @var $model AgentModel
     */
    protected $model;

    public function _initialize()
    {
        $this->model = new \app\common\model\Agent;
        parent::_initialize();
        //移除HTML标签
        $this->request->filter('trim,strip_tags,htmlspecialchars');
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['member','amapProvince', 'amapCity', 'amapDistricts'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try{
                    if (!Validate::is($params['password'], '\S{6,30}')) {
                        exception(__("Please input correct password"));
                    }
                    $params['salt'] = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                    $params['code'] = generateUniqueString();
                    //生成二维码
                    $qrcode_url = mkQrcodeCode(Env::get('app.app_host')."/agent/bind?code={$params['code']}",md5(time().rand(1000,9999)),'uploads/agent_qrcode/');
                    $params['bind_qrcode'] = $qrcode_url;
                    $result = $this->model->validate('Agent.add')->save($params);
                    if ($result === false) {
                        exception($this->model->getError());
                    }
                    Db::commit();
                }catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try {
                    if ($params['password']) {
                        if (!Validate::is($params['password'], '\S{6,30}')) {
                            exception(__("Please input correct password"));
                        }
                        $params['salt'] = Random::alnum();
                        $params['password'] = md5(md5($params['password']) . $params['salt']);
                    } else {
                        unset($params['password'], $params['salt']);
                    }
                    $params['code'] = $row['code'];
                    if (empty($row['code']))
                        $params['code'] = generateUniqueString();//获取8位唯一的字符串
                    if(empty($row['bind_qrcode'])){
                        //生成二维码
                        $qrcode_url = mkQrcodeCode(Env::get('app.app_host')."/agent/bind?code={$params['code']}",md5(time().rand(1000,9999)),'uploads/agent_qrcode/');
                        $params['bind_qrcode'] = $qrcode_url;
                    }
                    $result = $row->validate('Agent.edit')->save($params);
                    if ($result === false) {
                        exception($row->getError());
                    }

                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


//
//
//    public function close($ids)
//    {
//        try {
//            if (false === $this->model->update(['status' => AgentModel::STATUS_CLOSE], ['id' => $ids])) {
//                $this->error('更新失败');
//            }
//            $this->success();
//        } catch (Exception $exception) {
//            $this->error($exception->getMessage());
//        }
//    }
//
//    public function open($ids)
//    {
//        try {
//            if (false === $this->model->update(['status' => AgentModel::STATUS_OK], ['id' => $ids])) {
//                $this->error('更新失败');
//            }
//            $this->success();
//        } catch (Exception $exception) {
//            $this->error($exception->getMessage());
//        }
//
//    }


}